package controllers

import (
	"encoding/json"
	"fmt"
	"ztrxm1/db"
	"ztrxm1/models"

	beego "github.com/beego/beego/v2/server/web"
)

type MainController struct {
	beego.Controller
}

type Xsm struct {
	Name  string
	Sn    string
	Sex   string
	Grade string
}

func (c *MainController) Get() {
	var xs []*Xsm
	db.DB.Raw("select name,sn,sex,grade from chuanyou.classmates limit 10").Scan(&xs)
	c.Data["ztr"] = xs

	c.Data["姓名"] = "张庹然"
	c.Data["学号"] = "210320206008"
	c.TplName = "index.tpl"
}

func (c *MainController) Zc() {
	c.TplName = "zc.html"
}

func (c *MainController) Dl() {
	c.TplName = "dl.html"
}

func (c *MainController) Yzdl() {
	sn := c.GetString("sn")
	pswd := c.GetString("pswd")
	fmt.Println("收到了前端的数据:", sn, pswd)
	var currentPerson models.Classmates
	db.DB.Raw("select * from chuanyou.classmates where sn=?", sn).Scan(&currentPerson)
	if currentPerson.Pswd == pswd {
		c.Data["json"] = currentPerson
	} else {
		c.Data["json"] = nil
	}

	c.ServeJSON()
}

func (c *MainController) DoRegister() {
	var user models.Classmates
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &user)
	if err != nil {
		c.Data["json"] = "注册失败" + err.Error()
		c.ServeJSON()
		return
	}
	db.DB.Create(user)
	c.Data["json"] = "注册成功"
	c.ServeJSON()
}
